﻿using System;
using System.Data;
using System.Net.Json;
using Patent.CN;
using Patent.DBUtility;
using Patent.LJ;

/*************************************************************
 * GetJson.aspx
 * 
 * 该页面其实是一个转换，客户端发起请求到这个页面，本页面根据
 * 不同的请求要求，调用对应的逻辑代码，生成json字符串，然后发送
 * 给客户端。
 * 
 * ***********************************************************/

public partial class China_getJson : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            string act = Request["act"].ToString().Trim();
            string jsonString = string.Empty;
            //int topicID = 1;// Int32.Parse(context.Session["ID"].ToString());
            int topicID =  Convert.ToInt32(Session["topicID"].ToString());
            int start = 0;
            int limit = 0;
            int count = 0;
            string applicant = string.Empty;
            string queryWord = string.Empty;
            switch (act)
            {
                case "LocalAreaTree":
                    int type = -1;
                    
                    if (Request["type"] != null)
                    {
                        type = Int32.Parse(Request["type"]);
                        jsonString = GetLocalAreaTree(topicID, type);
                    }

                    break;
                case "OrientAreaAnalysisGrid":
                    
                    if (Request.QueryString["selected"] != null)
                    {
                        string nodeIds = Request.QueryString["selected"];
                        jsonString = China_GridData_OrientAreaAnalysisGrid(topicID, nodeIds);
                    }

                    break;
                case "ChineseTypeGridDefault":
                    jsonString = China_GridData_ChineseTypeGrid(topicID);
                    break;
                case "ChineseTypeGridFmzl":
                    if (Request["start"] != null)
                    {
                        start = Int32.Parse(Request["start"].ToString());
                    }

                    if (Request["limit"] != null)
                    {
                        limit = Int32.Parse(Request["limit"].ToString());
                    }

                    jsonString = China_GridData_ChineseTypeGridClassGrid("发明", topicID, start, limit);
                    break;
                case "ChineseTypeGridWgsj":

                    if (Request["start"] != null)
                    {
                        start = Int32.Parse(Request["start"].ToString());
                    }
                    
                    if (Request["limit"] != null)
                    {
                        limit = Int32.Parse(Request["limit"].ToString());
                    }
                    
                    jsonString = China_GridData_ChineseTypeGridClassGrid("外观", topicID, start, limit);
                    break;
                case "ChineseTypeGridSyxx":
                    if (Request["start"] != null)
                    {
                        start = Int32.Parse(Request["start"].ToString());
                    }
                    
                    if (Request["limit"] != null)
                    {
                        limit = Int32.Parse(Request["limit"].ToString());
                    }
                    
                    jsonString = China_GridData_ChineseTypeGridClassGrid("实用", topicID, start, limit);
                    break;
                case "ChineseTimeTrendGrid": //TimeTrendGrid
                    jsonString = China_GridData_TimeTrendGrid(topicID);
                    break;
                case "ChineseApplicantTree":
                    if (Request["count"] != null)
                    {
                        count = Int32.Parse(Request["count"].ToString());
                    }
                    
                    jsonString = China_Tree_Applicant(topicID, count);
                    break;
                case "ChineseApplicantPatentCountGrid":
                    jsonString = China_GridData_Applicant_PatentCount(topicID);
                    break;
                case "ChineseApplicantTrendTree":
                    applicant = Request["applicant"];
                    jsonString = China_Tree_ApplicantTrendtree(topicID, applicant);
                    break;
                case "ChineseApplicantTrendGrid":
                    applicant = Request.QueryString["applicant"];
                    jsonString = China_GridData_ApplicantTrend(topicID, applicant);
                    break;
                // 专利分析：申请人分析 数量分析，发明专利申请人列表
                case "NameOfFMZLApplicant":
                    jsonString = China_Tree_NameOfApplicantFMZL(topicID);
                    break;
                case "AllApplicant":
                    if (Request["start"] != null)
                    {
                        start = Int32.Parse(Request["start"].ToString());
                    }

                    if (Request["limit"] != null)
                    {
                        limit = Int32.Parse(Request["limit"].ToString());
                    }
                    else
                    {
                        limit = 20;
                    }

                    if (Request["query"] != null)
                    {
                        queryWord = Request["query"].ToString();
                    }

                    jsonString = China_Grid_AllApplicantsName(topicID, start, limit,queryWord);
                    break;

                default:
                    jsonString = "No act is specified!";
                    break;
            }

            Response.ContentType = "text/plain";
            Response.Write(jsonString);
            Response.End();
        }
        catch (System.FormatException)
        {
            Response.Write("");
            Response.End();
        }
        catch (System.NullReferenceException ex)
        {
            Response.Write(ex.ToString());
            Response.End();
        }
    }

    private string China_Grid_AllApplicantsName(int topicID,int start, int limit,string  queryWord)
    {
        string returnString = string.Empty;
        ChinaAnalysis cnAnalysis = new ChinaAnalysis();
        Topic topic = new Topic(topicID);
        cnAnalysis.M_topicTable = topic.InfoTable;
        DataTable dt= cnAnalysis.GetNameOfApplicants(start, limit, queryWord);
        
        JsonArrayCollection jsonArray = new JsonArrayCollection();
        jsonArray.Name = "info";
        for (int i = 0; i < dt.Rows.Count; i++)
        {
            JsonObjectCollection collection = new JsonObjectCollection();
            collection.Add(new JsonStringValue("Name", dt.Rows[i]["申请人"].ToString()));
            
            jsonArray.Insert(jsonArray.Count, collection);
        }
        int totalCount = cnAnalysis.GetNameOfApplicantsCount(queryWord);
        returnString = "{\"totalCount\":\"" + totalCount + "\"," + jsonArray.ToString() + "}";
        return returnString;
    }

    private string China_Tree_NameOfApplicantFMZL(int topicID)
    {
        ChinaAnalysis cnAnalysis = new ChinaAnalysis();
        Topic topic = new Topic(topicID);
        cnAnalysis.M_topicTable = topic.InfoTable;
        DataTable data = cnAnalysis.GetNameOfFMZLApplicants();
        JsonObjectCollection collection;
        JsonArrayCollection jsonStringCollection = new JsonArrayCollection();
        for (int i = 0; i < data.Rows.Count; i++)
        {
            collection = new JsonObjectCollection();
            string applicantName = data.Rows[i]["申请人"].ToString();
            collection.Add(new JsonStringValue("id", applicantName));
            collection.Add(new JsonStringValue("text", applicantName));
                collection.Add(new JsonStringValue("icon", "inc/images/icons/user.png"));
            collection.Add(new JsonBooleanValue("leaf", true));
            collection.Add(new JsonBooleanValue("checked", false));
            jsonStringCollection.Insert(jsonStringCollection.Count, collection);
        }

        return jsonStringCollection.ToString();
    }

    private string China_GridData_ApplicantTrend(int topicID, string applicant)
    {
        if (!string.IsNullOrEmpty(applicant))
        {
            ChinaAnalysis cnAnalysis = new ChinaAnalysis();
            Topic topic = new Topic(topicID);
            cnAnalysis.M_topicTable = topic.InfoTable;
            DataTable data = cnAnalysis.GetApplicantTrand(topicID.ToString(), topic.InfoTable, applicant);

            //json数据流
            JsonObjectCollection collection;
            JsonArrayCollection s = new JsonArrayCollection();
            s.Name = "result";

            for (int i = 0; i < data.Rows.Count; i++)
            {
                collection = new JsonObjectCollection();
                collection.Add(new JsonStringValue("year", data.Rows[i]["年份"].ToString()));
                collection.Add(new JsonStringValue("syxx", data.Rows[i]["实用新型"].ToString()));
                collection.Add(new JsonStringValue("fmzl", data.Rows[i]["发明专利"].ToString()));
                collection.Add(new JsonStringValue("wgsj", data.Rows[i]["外观设计"].ToString()));
                collection.Add(new JsonStringValue("count", data.Rows[i]["总计"].ToString()));

                s.Insert(s.Count, collection);
            }

            return "{" + s.ToString() + "}";
        }
        else
        {
            return "";
        }
        
    }

    private string China_Tree_ApplicantTrendtree(int topicID, string applicant)
    {
       
        if (!string.IsNullOrEmpty(applicant))
        {
            ChinaAnalysis cnAnalysis = new ChinaAnalysis();
            Topic topic = new Topic(topicID);
            cnAnalysis.M_topicTable = topic.InfoTable;
            DataTable data = cnAnalysis.GetApplicantTrendTree(applicant);

            //json数据流
            JsonObjectCollection collection;
            JsonArrayCollection s = new JsonArrayCollection();
            //s.Name = "result";


            for (int i = 0; i < data.Rows.Count; i++)
            {
                collection = new JsonObjectCollection();
                collection.Add(new JsonStringValue("id", i.ToString()));
                collection.Add(new JsonStringValue("text", data.Rows[i]["申请人"].ToString()));
                collection.Add(new JsonBooleanValue("leaf", true));
                s.Insert(s.Count, collection);
            }

            return s.ToString();
        }
        return "";
    }

    private string China_GridData_Applicant_PatentCount(int topicID)
    {
        string returnString = string.Empty;
        if (Request["applicants"] == null)
        {
            return "";
        }

        ChinaAnalysis cnAnalysis = new ChinaAnalysis(Convert.ToInt32(topicID));
        if (cnAnalysis.IsChineseTopic())
        {
            string[] applicants = Server.UrlDecode(Request["applicants"]).Split('|');
            DataTable dt = cnAnalysis.GetApplicantSumTable(applicants);
            JsonArrayCollection jsonArray = new JsonArrayCollection();
            jsonArray.Name = "applicant";
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                JsonObjectCollection collection = new JsonObjectCollection();
                collection.Add(new JsonStringValue("p_applicant", dt.Rows[i]["申请人"].ToString()));
                collection.Add(new JsonStringValue("psyxx", dt.Rows[i]["实用新型"].ToString()));
                collection.Add(new JsonStringValue("pfmzl", dt.Rows[i]["发明专利"].ToString()));
                collection.Add(new JsonStringValue("pwgsj", dt.Rows[i]["外观设计"].ToString()));
                collection.Add(new JsonStringValue("psum", dt.Rows[i]["总计"].ToString()));
                collection.Add(new JsonStringValue("replace", dt.Rows[i]["标志"].ToString()));
                jsonArray.Insert(jsonArray.Count, collection);
            }
            returnString = "{" + jsonArray.ToString() + "}";
        }
        return returnString;
    }

    private string China_Tree_Applicant(int topicID, int count)
    {
        string returnString = string.Empty;
        ChinaAnalysis cnAnalysis = new ChinaAnalysis(Convert.ToInt32(topicID));
        if (cnAnalysis.IsChineseTopic())
        {
            DataTable dt = cnAnalysis.GetApplySumTable(count);
            JsonArrayCollection jsonArray = new JsonArrayCollection();
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                JsonObjectCollection collection = new JsonObjectCollection();
                collection.Add(new JsonStringValue("id", i.ToString()));
                collection.Add(new JsonStringValue("text", dt.Rows[i]["申请人"].ToString()));
                collection.Add(new JsonBooleanValue("leaf", true));
                jsonArray.Insert(jsonArray.Count, collection);
            }
            returnString = jsonArray.ToString();

        }
        return returnString;
    }

    /// <summary>
    /// 中国专项：原产区分析 左树
    /// </summary>
    /// <param name="topicID"></param>
    /// <param name="type"></param>
    /// <returns></returns>
    private string GetLocalAreaTree(int topicID, int type)
    {
        string returnString = string.Empty;

        Topic topic = new Topic(topicID);
        string localTable = topic.OriginalTable;//原产区表名
        SQLHelper helper = new SQLHelper();
        DataSet data = new DataSet();
        string sql;
        if (type == 0)//省份//type=0为省份，type=1为国家
        {
            sql = "select 名称,国省代码 from " + localTable + ",dm_sq where 国省代码>='00' and 国省代码<='99' and Len([国省代码])=2 and 国省代码=代码 order by [国省代码]";
        }
        else//国家
        {
            sql = "select 名称,国省代码 from " + localTable + ",dm_gj where 国省代码>='AA' and 国省代码<='ZZ' and Len([国省代码])=2 and 国省代码=代码 order by [国省代码]";
        }
        helper.RunSQL(sql, ref data);

        JsonObjectCollection collection;
        JsonArrayCollection s = new JsonArrayCollection();

        for (int i = 0; i < data.Tables[0].Rows.Count; i++)
        {
            collection = new JsonObjectCollection();
            collection.Add(new JsonStringValue("id", data.Tables[0].Rows[i]["国省代码"].ToString()));
            collection.Add(new JsonStringValue("text", data.Tables[0].Rows[i]["名称"].ToString()));
            collection.Add(new JsonBooleanValue("leaf", true));
            collection.Add(new JsonBooleanValue("checked", false));
            s.Insert(s.Count, collection);
        }
        returnString = s.ToString();
        return returnString;
    }

    /// <summary>
    /// 中国专项：原产区分析 表格数据
    /// </summary>
    /// <param name="topicID"></param>
    /// <param name="nodeIds"></param>
    /// <returns></returns>
    private string China_GridData_OrientAreaAnalysisGrid(int topicID, string nodeIds)
    {

        //Patent.Topic topic = new Topic(Convert.ToInt32(Session["topicID"].ToString()));
        Topic topic = new Topic(topicID);
        string localTable = topic.OriginalTable;//原产区表名
        //string local = "34,12";

        if (string.IsNullOrEmpty(nodeIds))
        {
            Response.End();
            Response.Flush();
        }
        string[] area = nodeIds.Split(',');
        ChinaAnalysis ana = new ChinaAnalysis();
        DataTable table = ana.GetLocalArea(area, localTable);

        JsonObjectCollection collection;
        JsonArrayCollection s = new JsonArrayCollection();
        s.Name = "result";

        for (int i = 0; i < table.Rows.Count; i++)
        {
            collection = new JsonObjectCollection();

            collection.Add(new JsonStringValue("dm", table.Rows[i]["dm"].ToString()));
            collection.Add(new JsonStringValue("mc", table.Rows[i]["mc"].ToString()));
            collection.Add(new JsonStringValue("sy", table.Rows[i]["sy"].ToString() + "(" + table.Rows[i]["syper"].ToString() + ")"));
            collection.Add(new JsonStringValue("fm", table.Rows[i]["fm"].ToString() + "(" + table.Rows[i]["fmper"].ToString() + ")"));
            collection.Add(new JsonStringValue("wg", table.Rows[i]["wg"].ToString() + "(" + table.Rows[i]["wgper"].ToString() + ")"));
            collection.Add(new JsonStringValue("zj", table.Rows[i]["zj"].ToString() + "(" + table.Rows[i]["zjper"].ToString() + ")"));

            s.Insert(s.Count, collection);
        }
        string result = "{" + s.ToString() + "}";
        return result;
    }

    private string China_GridData_ChineseTypeGrid(int topicID)
    {
        string returnString = string.Empty;
        ChinaAnalysis cnAnalysis = new ChinaAnalysis(topicID);
        if (cnAnalysis.IsChineseTopic())
        {
            //实用新型
            int syxx = cnAnalysis.GetCount("syxx");
            //外观设计
            int wgsj = cnAnalysis.GetCount("wgzl");
            //发明专利
            int fmzl = cnAnalysis.GetCount("fmzl");
            //总计
            int sum = cnAnalysis.GetAllPatentsCount();


            JsonArrayCollection jsonArray = new JsonArrayCollection();
            jsonArray.Name = "basic";

            JsonObjectCollection jsonSYXX = new JsonObjectCollection();
            JsonObjectCollection jsonWGSJ = new JsonObjectCollection();
            JsonObjectCollection jsonFMZL = new JsonObjectCollection();

            jsonFMZL.Add(new JsonStringValue("ptype", "发明专利"));
            jsonFMZL.Add(new JsonStringValue("pcount", fmzl.ToString()));
            jsonFMZL.Add(new JsonStringValue("percent", (float)fmzl / sum * 100 + "%"));

            jsonSYXX.Add(new JsonStringValue("ptype", "实用新型"));
            jsonSYXX.Add(new JsonStringValue("pcount", syxx.ToString()));
            jsonSYXX.Add(new JsonStringValue("percent", (float)syxx / sum * 100 + "%"));

            jsonWGSJ.Add(new JsonStringValue("ptype", "外观设计"));
            jsonWGSJ.Add(new JsonStringValue("pcount", wgsj.ToString()));
            jsonWGSJ.Add(new JsonStringValue("percent", (float)wgsj / sum * 100 + "%"));

            jsonArray.Insert(jsonArray.Count, jsonFMZL);
            jsonArray.Insert(jsonArray.Count, jsonSYXX);
            jsonArray.Insert(jsonArray.Count, jsonWGSJ);

            returnString = "{" + jsonArray.ToString() + "}";
        }
        return returnString;
    }


    /// <summary>
    /// 获取发明专利详细信息
    /// </summary>
    /// <param name="topicID"></param>
    /// <returns></returns>
    private string China_GridData_ChineseTypeGridClassGrid(string type, int topicID, int start, int limit)
    {
        string returnString = string.Empty;
        ChinaAnalysis cnAnalysis = new ChinaAnalysis(topicID);
        if (cnAnalysis.IsChineseTopic())
        {

            DataTable dt = cnAnalysis.GetPatentInfoTable(type, start, limit);
            int totalCount = 0;
            if (type == "发明")
            {
                totalCount = cnAnalysis.GetCount("fmzl");
            }
            else if (type == "实用")
            {
                totalCount = cnAnalysis.GetCount("syxx");
            }
            else if (type == "外观")
            {
                totalCount = cnAnalysis.GetCount("wgzl");
            }

            JsonArrayCollection jsonArray = new JsonArrayCollection();
            jsonArray.Name = "info";
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                JsonObjectCollection collection = new JsonObjectCollection();
                collection.Add(new JsonStringValue("applyNo", dt.Rows[i]["申请号"].ToString()));
                collection.Add(new JsonStringValue("publicDate", dt.Rows[i]["公开日"].ToString()));
                collection.Add(new JsonStringValue("publicID", dt.Rows[i]["公开号"].ToString()));
                collection.Add(new JsonStringValue("applyDate", dt.Rows[i]["申请日"].ToString()));
                collection.Add(new JsonStringValue("patentID", dt.Rows[i]["专利号"].ToString()));
                collection.Add(new JsonStringValue("cardDate", dt.Rows[i]["颁证日"].ToString()));

                collection.Add(new JsonStringValue("applicant", dt.Rows[i]["申请人"].ToString()));
                collection.Add(new JsonStringValue("classID", dt.Rows[i]["主分类号"].ToString()));
                collection.Add(new JsonStringValue("pName", dt.Rows[i]["名称"].ToString()));
                collection.Add(new JsonStringValue("countryCode", dt.Rows[i]["国省代码"].ToString()));
                jsonArray.Insert(jsonArray.Count, collection);
            }

            returnString = "{\"totalCount\":\"" + totalCount.ToString() + "\"," + jsonArray.ToString() + "}";
        }
        return returnString;
    }

    private string China_GridData_TimeTrendGrid(int topicID)
    {

        string returnString = string.Empty;
        ChinaAnalysis cnAnalysis = new ChinaAnalysis(topicID);
        if (cnAnalysis.IsChineseTopic())
        {
            DataTable dt = cnAnalysis.GetTrendTable();
            JsonArrayCollection jsonArray = new JsonArrayCollection();
            jsonArray.Name = "timeTrend";
            int sum = 0;
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                JsonObjectCollection collection = new JsonObjectCollection();
                collection.Add(new JsonStringValue("pyear", dt.Rows[i]["年份"].ToString()));
                collection.Add(new JsonStringValue("psyxx", dt.Rows[i]["实用新型"].ToString()));
                collection.Add(new JsonStringValue("pwgsj", dt.Rows[i]["外观设计"].ToString()));
                collection.Add(new JsonStringValue("pfmzl", dt.Rows[i]["发明专利"].ToString()));
                sum = Int32.Parse(dt.Rows[i]["实用新型"].ToString()) + Int32.Parse(dt.Rows[i]["外观设计"].ToString()) + Int32.Parse(dt.Rows[i]["发明专利"].ToString());
                collection.Add(new JsonStringValue("psum", sum.ToString()));
                jsonArray.Insert(jsonArray.Count, collection);
            }
            returnString = "{" + jsonArray.ToString() + "}";
        }

        return returnString;
    }
}
